using System.Collections.Generic;
using Castle.ActiveRecord;
using Castle.Components.Validator;
using KenEgozi.Com.Domain.Projections;

namespace KenEgozi.Com.Domain.Aggregates.Post
{
	[Import(typeof(ArchiveEntry), "ArchiveEntry")]
	[Import(typeof(TagCloudEntry), "TagCloudEntry")]
	[ActiveRecord(Lazy = true)]
	public class Post
	{
		readonly int _id = default(int);
		readonly Lifecycle _lifecycle = new Lifecycle(); 
		string _title;
		string _permalink;
		string _content;
		readonly int _commentCount = default(int);
		readonly IList<Comment> _comments = new List<Comment>();
		readonly IList<Tag.Tag> _tags = new List<Tag.Tag>();
		
		[Property(Access = PropertyAccess.NosetterCamelcaseUnderscore)]
		[ValidateNonEmpty]
		public virtual string Title
		{
			get { return _title; }
			set { _title = value; }
		}

		[Property(Access = PropertyAccess.NosetterCamelcaseUnderscore)]
		public virtual string Permalink
		{
			get { return _permalink; }
			internal set { _permalink = value; }
		}

		[Property(Access = PropertyAccess.NosetterCamelcaseUnderscore,ColumnType="StringClob" )]
		public virtual string Content
		{
			get { return _content; }
			set { _content = value; }
		}

		[HasMany(Lazy = true, Access = PropertyAccess.NosetterCamelcaseUnderscore, Cascade=ManyRelationCascadeEnum.AllDeleteOrphan)]
		public virtual IList<Comment> Comments
		{
			get { return _comments; }
		}

		public virtual IList<Comment> NewComments
		{
			get { 
				List<Comment> comments = new List<Comment>(Comments);
				return comments.FindAll(delegate(Comment comment)
				{
					return comment.Status == CommentStatus.ProbableOk;
				});
			}
		}

		[Property(Access = PropertyAccess.NosetterCamelcaseUnderscore, Formula="(SELECT COUNT(c.Id) FROM comments c WHERE c.Status = 2 and c.PostId = Id)")]
		public virtual int CommentCount
		{
			get { return _commentCount; }
		}

		[HasAndBelongsToMany(
			Table = "PostTagging",
			ColumnKey = "PostId",
			ColumnRef = "TagId",
			Fetch = FetchEnum.SubSelect,
			Access = PropertyAccess.NosetterCamelcaseUnderscore)]
		public virtual IList<Tag.Tag> Tags
		{
			get { return _tags; }
		}

		[PrimaryKey(Access = PropertyAccess.NosetterCamelcaseUnderscore)]
		public virtual int Id
		{
			get { return _id; }
		}

		[Nested(Access = PropertyAccess.NosetterCamelcaseUnderscore)]
		public virtual Lifecycle Lifecycle
		{
			get { return _lifecycle; }
		}
	}
}
